package server;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;

import common.IUI;
import common.Profile;

public class Room {

    private int counter = 0;
    private int roomSize;   
    private Map<Profile, IUI> roomClients;
    
    public Room(Profile profile, IUI userUI,int roomSize) {
        this.roomSize = roomSize;
        roomClients = new HashMap<Profile,IUI>();
        addToRoom(profile, userUI);        
    } 
    
    public int getRoomSize() {
    	return roomSize;
    }
    
    public int getNumOfPlayersInRoom() {
    	return counter;
    }
    
    public boolean addToRoom(Profile profile, IUI userUI) {
        if (!isFull()) {
            for (Profile p : roomClients.keySet()) {
                if (p.getUserName().equals(profile.getUserName())) {
                    return false;
                }
            }
            
            
            
            roomClients.put(profile, userUI);
            counter++;
            if (!isFull())
            {
            	if (profile.isGuest()) {
            		sendMessageToRoom(profile + " has entered the room.\n");
            	} else {
                    sendMessageToRoom(profile + " has entered the room, Their rating is "+profile.getRating()+"\n");
            	}
                sendMessageToRoom("Currently " + counter + " players out of " + roomSize + " players\n");
            }
            else
            {
                sendMessageToRoom(profile + " has entered the room. Starting game!\n");
            }
            return true;
        } else {
            return false;
        }
    }
    
    
    public boolean isFull() {
        return (counter == roomSize);
    }
    
    public Map<Profile, IUI> getClients() {
        return roomClients;
    }
    
    private void sendMessageToRoom(String message)
    {
        for (IUI playerUI : roomClients.values())
        {
            try {
                playerUI.printMessage(message);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
}
